package org.calzz.jajb.converter;

import java.lang.reflect.Array;
import java.util.List;

import org.calzz.jajb.JsonDeserializer;
import org.calzz.jajb.JsonSerializer;
import org.calzz.jajb.io.IWriter;
import org.springframework.core.MethodParameter;

/**
 * The default converter for array types.
 * @author Marek Brodziak <marek.brodziak@gmail.com>
 * @author Piotr Pejas <piotr.pejas@gmail.com>
 * @since Feb 10, 2008
 */
public class ArrayConverter implements IConverter {

	/*
	 * (non-Javadoc)
	 * @see org.jamjam.jajb.converter.IConverter#canConvert(java.lang.Class)
	 */
	public boolean canConvert(Class<?> clazz) {
		return clazz.isArray();
	}

	/*
	 * (non-Javadoc)
	 * @see org.jamjam.jajb.converter.IConverter#marshal(java.lang.Object,
	 *      java.lang.String, org.jamjam.jajb.io.IWriter,
	 *      org.jamjam.jajb.JsonSerializer)
	 */
	public void marshal(Object obj, String name, IWriter writer, JsonSerializer serializer) {
		int length = Array.getLength(obj);
		writer.startArray(name);
		for (int i = 0; i < length; i++) {
			serializer.process(Array.get(obj, i), null, writer);
		}
		writer.endArray();
	}

	/*
	 * (non-Javadoc)
	 * @see org.jamjam.jajb.converter.IConverter#unmarshal(java.lang.Object,
	 *      java.lang.Class, org.jamjam.jajb.JsonDeserializer)
	 */
	public <T> Object unmarshal(Object env, Class<T> clazz, JsonDeserializer deserializer, MethodParameter methodParam) {
		List<?> in = (List<?>) env;
		Object array = Array.newInstance(clazz.getComponentType(), in.size());
		int i = 0;
		for (Object o : in) {
			Array.set(array, i, deserializer.process(o, clazz.getComponentType(), null));
			i++;
		}
		return array;
	}
}
